﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using TmU220PrintHelperV2d0.ControlUi;
using TmU220PrintHelperV2d0.Entity;
using TmU220PrintHelperV2d0.Service;
using TmU220PrintHelperV2d0.Singleton;
using ZhangLogSysV1d0;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Configuration;
using System.Threading;

namespace PrinterControl
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            Init();
        }
        public void Init()
        {
            try
            {
                string apiUrl = PhpApiSetSingletonV1d0.Instance.GetProjectMainUrl();
                TitleBarString = "創域餐飲管理系統-TMU220打印機打印管理-v1.059["+apiUrl+"]";
                StartTime = DateTime.Now;
                this.Text = TitleBarString;
                PrinterInfoSet = new PrinterInfoSetV2d0();
                PrinterMonitorList = new List<TmU220PrinterMonitorV2d0>();
                VirtualPrinterMonitorList = new List<VirtualPrinterMonitorV2d0>();
                TaskTraceInfoList = new List<PrintTaskTraceInfoV2d0>();
                MainTaskQueue = new ConcurrentQueue<PrintTaskV2d0>();
                // 本地打印机配置文件名
                PrinterCfgFilename = System.IO.Directory.GetCurrentDirectory() + @"\parameter\PrinterInfo.xml";
                //从配置文件中读取模板文件名,任务的有效时长（任务生成后，若干分钟内有效）
                //UsingPrintTempletName = Properties.Settings.Default.PrintTempletName;
                //TimeOutOfTask = Properties.Settings.Default.TimeoutOfTask;
                TimeOutOfTask = SysCfgInfoSingletonV1d0.Instance.GetTimeoutOfTask();
                //TaskApiUrl = Properties.Settings.Default.TaskApiUrl;
                TaskApiUrl = SysCfgInfoSingletonV1d0.Instance.GetApiMainUrl();
                //IntervalOfCheckTask = Properties.Settings.Default.IntervalOfCheckTask;
                IntervalOfCheckTask = SysCfgInfoSingletonV1d0.Instance.GetIntervalOfCheckTask();
                IsGetPrinterCfgFromRemote = SysCfgInfoSingletonV1d0.Instance.GetIsGetPrinterCfgFromMemote();
                ShopId = SysCfgInfoSingletonV1d0.Instance.GetShopId();
                //TimeOutOfTask = Properties.Settings.Default.TimeoutOfTask;
                //ShopId = Properties.Settings.Default.ShopId;
                //zhangfujian 2019-02-16
                //得到打印日志数据类，从文件读取，或者新建
                PrintLog = LoadPrintLogFromFile();
                iconError = new Icon("resources/error.ico");
                iconNormal = new Icon("resources/normal.ico");
                notifyIcon1.Icon = iconNormal;
                //启动每日定时系统清理
                startCleanAtFixedTime();
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
        /// <summary>
        /// 启动打印任务填充线程
        /// </summary>
        private void ThreadFillPrintTaskStart()
        {
            if(ThreadFillPrintTask ==null)
            {
                ThreadFillPrintTask = new ThreadFillPrintTaskQueueV3d0(MainTaskQueue, TimeOutOfTask, IntervalOfCheckTask);
                ThreadFillPrintTask.DownloadPrintTaskOverEvent += ProcDownloadPrintTaskOverEvent;
                ThreadFillPrintTask.Running = true;
                ThreadFillPrintTask.Thread_index = 1;
                ThreadFillPrintTask.StartThread();
            }
            else
            {
                ThreadFillPrintTask.DownloadPrintTaskOverEvent -= ProcDownloadPrintTaskOverEvent;
                ThreadFillPrintTask.StopThread();
                ThreadFillPrintTask = null;
                ThreadFillPrintTask = new ThreadFillPrintTaskQueueV3d0(MainTaskQueue, TimeOutOfTask, IntervalOfCheckTask);
                ThreadFillPrintTask.DownloadPrintTaskOverEvent += ProcDownloadPrintTaskOverEvent;
                ThreadFillPrintTask.Running = true;
                ThreadFillPrintTask.Thread_index = 1;
                ThreadFillPrintTask.StartThread();
            }
        }
        public PrinterInfoSetV2d0 PrinterInfoSet;
        public List<PrintTaskTraceInfoV2d0> TaskTraceInfoList;
        public String PrinterCfgFilename { get; set; }
        /// <summary>
        /// 打印机监视器控件列表
        /// </summary>
        public List<TmU220PrinterMonitorV2d0> PrinterMonitorList;
        public List<VirtualPrinterMonitorV2d0> VirtualPrinterMonitorList;
        /// <summary>
        /// 填充打印队列的线程
        /// </summary>
        public ThreadFillPrintTaskQueueV3d0 ThreadFillPrintTask = null;
        public bool testSign=false;
        /// <summary>
        /// 主任务队列
        /// </summary>
        public ConcurrentQueue<PrintTaskV2d0> MainTaskQueue;
        private PrintLogV2d0 PrintLog = null;
        /// <summary>
        /// 打印任务超时时间，这个时间之外的打印任务即使未打印也不会加入打印队列
        /// </summary>
        public int TimeOutOfTask { get; set; }
        /// <summary>
        /// 打印任务检查的间隔时间 单位秒
        /// </summary>
        public int IntervalOfCheckTask { get; set; }
        public bool IsGetPrinterCfgFromRemote { get; set; }
        /// <summary>
        /// 所属shop的shop_uid
        /// </summary>
        public int ShopId { get; set; }
        public string TitleBarString { get; set; }

        public DateTime StartTime { get; set; }
        private Icon iconNormal;
        private Icon iconError;
        /// <summary>
        /// 打印任务的api接口的URL
        /// </summary>
        public string TaskApiUrl { get; set; }

        public PrintLogV2d0 LoadPrintLogFromFile()
        {
            PrintLogV2d0 log = null;
            try
            {
                string basePath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\";
                if (!Directory.Exists(basePath))
                    Directory.CreateDirectory(basePath);
                string xmlFilename = basePath +
                    string.Format("PrintCompleteLog-{0}.xml", DateTime.Now.ToString("yyyyMMdd"));
                if (File.Exists(xmlFilename))
                {
                    log = HotchPotchV2d0.ReadFromXmlFile<PrintLogV2d0>(xmlFilename);
                }
                else
                {
                    log = new PrintLogV2d0();
                }
               
            }
            catch(Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return log;
        }


        private void button1_Click(object sender, EventArgs e)
        {
            FirePrintersMonitor();
            
        }
        private bool CheckPrinerCfgFileIsExist()
        {
            if (File.Exists(PrinterCfgFilename)) return true;
            else return false;
        }
        /// <summary>
        /// 启动打印机监控
        /// </summary>
        private void FirePrintersMonitor()
        {
            try
            {
                if(IsGetPrinterCfgFromRemote) PrinterInfoSet = PrinterInfoSetSingletonV2d0.Instance.GetPrinterInfoSet();
                else
                {
                    //如果本地打印机配置文件不存在就手工编辑
                    if (File.Exists(PrinterCfgFilename))
                    {
                        PrinterInfoSet = HotchPotchV2d0.ReadFromXmlFile<PrinterInfoSetV2d0>(PrinterCfgFilename);
                        PrinterInfoSet.PrinterInfoList = PrinterInfoSet.PrinterInfoList.FindAll(x => x.is_active.HasValue && x.is_active.Value);
                    }
                    else
                    {
                        MessageBox.Show("未找到本地打印机配置文件,请手工编辑打印机配置信息！");
                        FormPrinterSetting formPrinterSetting = new FormPrinterSetting();
                        formPrinterSetting.ShowDialog();
                        PrinterInfoSet = formPrinterSetting.InfoSet;
                    }
                }

                // 启动打印任务分发循环
                timerTaskDispatch.Enabled = true;
                // 在清空物理打印机监控列表在之前，释放物理打印机监控面板的资源
                PrinterMonitorList.Clear();
                this.tableLayout_RealPrinters.Controls.Clear();
                // ip不重复的打印机列表
                var uniquePrintersOfIp = from p in PrinterInfoSet.PrinterInfoList
                                         group p by new { p.ip } //or group by new {p.ID, p.Name, p.Whatever}
                                         into mygroup
                                         select mygroup.FirstOrDefault();
                PrinterMonitorList.Clear();
                this.tableLayout_RealPrinters.Controls.Clear();
                //物理打印机
                foreach (var printer in uniquePrintersOfIp)
                {
                    TmU220PrinterMonitorV2d0 pMonitor = new TmU220PrinterMonitorV2d0(printer);
                    pMonitor.PrintCompleteEvent -= ProcPrintCompleteEvent;
                    pMonitor.PrintCompleteEvent += ProcPrintCompleteEvent;
                    this.tableLayout_RealPrinters.Controls.Add(pMonitor);
                    PrinterMonitorList.Add(pMonitor);
                }
                // 在清空虚拟打印机监控列表之前,释放想虚拟打印机监控面板的资源
                VirtualPrinterMonitorList.Clear();
                this.tableLayout_VirtualPrinters.Controls.Clear();
                foreach (var printer in PrinterInfoSet.PrinterInfoList)
                {
                    VirtualPrinterMonitorV2d0 pMonitor = new VirtualPrinterMonitorV2d0();
                    var realePrinterMonitor = PrinterMonitorList.FirstOrDefault(x => x.PrinterIp == printer.ip);
                    if (realePrinterMonitor != null)
                    {
                        pMonitor.Init(printer, realePrinterMonitor);
                        this.tableLayout_VirtualPrinters.Controls.Add(pMonitor);
                        VirtualPrinterMonitorList.Add(pMonitor);
                    }
                }

            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }

        }
        /// <summary>
        /// 得到打印机配置信息
        /// </summary>
        /// <returns></returns>
        private PrinterInfoSetV2d0 GetPrinterInfo(int shopId=0)
        {
            PrinterInfoSetV2d0 infoSet = null;
            try
            {
                infoSet= PrinterInfoSetSingletonV2d0.Instance.GetPrinterInfoSet();
                return infoSet;
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
            return infoSet;
        }

        private void button2_Click(object sender, EventArgs e)
        {
        }

        private PrintTaskV2d0 GetPrintTaskOfPrinterTesting(VirtualPrinterMonitorV2d0 printerMonitor)
        {
            PrintTaskV2d0 pTask = new PrintTaskV2d0();

            PrintTaskItemV2d0 taskItem1 = new PrintTaskItemV2d0();
            taskItem1.PrintSequence = 1;
            taskItem1.Content = "PrintTest";
            taskItem1.FormatOfContent.Align = "Center";
            taskItem1.FormatOfContent.PrintMode = "Text";
            taskItem1.FormatOfContent.IsDoubleWidth = true;
            taskItem1.FormatOfContent.IsDoubleHeight = true;
            pTask.PrintTaskItemList.Add(taskItem1);
            PrintTaskItemV2d0 taskItem2 = new PrintTaskItemV2d0();
            taskItem2.PrintSequence = 2;
            taskItem2.Content = "Printer IP:" + printerMonitor.PrinterIp;
            taskItem2.FormatOfContent.Align = "Left";
            taskItem2.FormatOfContent.PrintMode = "Text";
            pTask.PrintTaskItemList.Add(taskItem2);

            PrintTaskItemV2d0 taskItem3 = new PrintTaskItemV2d0();
            taskItem3.PrintSequence = 3;
            taskItem3.Content = "Printer Port:" + printerMonitor.PrinterPort;
            taskItem3.FormatOfContent.Align = "Left";
            taskItem3.FormatOfContent.PrintMode = "Text";
            taskItem3.FormatOfContent.IsUnderLine = false;
            pTask.PrintTaskItemList.Add(taskItem3);

            PrintTaskItemV2d0 taskItem4 = new PrintTaskItemV2d0();
            taskItem4.PrintSequence = 4;
            taskItem4.Content = "Printer Name:" + printerMonitor.PrinterName;
            taskItem4.FormatOfContent.Align = "Left";
            taskItem4.FormatOfContent.PrintMode = "Text";
            taskItem4.FormatOfContent.IsUnderLine = false;
            pTask.PrintTaskItemList.Add(taskItem4);

            PrintTaskItemV2d0 taskItem5 = new PrintTaskItemV2d0();
            taskItem5.PrintSequence = 5;
            taskItem5.Content = "Backup Printer Name:" + printerMonitor.BackupPrinterName;
            taskItem5.FormatOfContent.Align = "Left";
            taskItem5.FormatOfContent.PrintMode = "Text";
            taskItem5.FormatOfContent.IsUnderLine = false;
            pTask.PrintTaskItemList.Add(taskItem5);

            PrintTaskItemV2d0 taskItem6 = new PrintTaskItemV2d0();
            taskItem6.PrintSequence = 5;
            taskItem6.Content = "Printing Time:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            taskItem6.FormatOfContent.Align = "Left";
            taskItem6.FormatOfContent.PrintMode = "Text";
            taskItem6.FormatOfContent.IsUnderLine = false;
            pTask.PrintTaskItemList.Add(taskItem6);
            //蟹肉鮮蜆蕃茄忌廉汁意粉珍寶虎蝦胃口意大利飯配三文魚籽 $128.00

            PrintTaskItemV2d0 taskItem7 = new PrintTaskItemV2d0();
            taskItem7.PrintSequence = 6;
            taskItem7.Content = "Device Type:" + printerMonitor.DeviceType;
            taskItem7.FormatOfContent.Align = "Left";
            taskItem7.FormatOfContent.PrintMode = "Text";
            taskItem7.FormatOfContent.IsUnderLine = false;
            taskItem7.FormatOfContent.FontColor = "Red";
            pTask.PrintTaskItemList.Add(taskItem7);
            PrintTaskItemV2d0 taskItem8 = new PrintTaskItemV2d0();
            taskItem8.PrintSequence = 8;
            taskItem8.Content = "---------Successful!!!--------";
            taskItem8.FormatOfContent.Align = "Center";
            taskItem8.FormatOfContent.PrintMode = "Text";
            taskItem8.FormatOfContent.IsUnderLine = false;
            taskItem8.FormatOfContent.FontColor = "Red";
            pTask.PrintTaskItemList.Add(taskItem8);

            pTask.DataOfPrintTask.printer = printerMonitor.PrinterName;
            pTask.DataOfPrintTask.addtime = DateTime.Now;

            return pTask;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            timerTaskDispatch.Enabled = true;// = !timer1.Enabled;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            testSign = !testSign;
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason== CloseReason.UserClosing)
            {
                e.Cancel= true;          //取消关闭操作
                //表现为不关闭窗体
                this.Hide();              //隐藏窗体
            }            
        }
      
        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            
        }

        private void ShowWindowsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();                               //窗体显示
            this.WindowState  = FormWindowState.Normal;  //窗体状态默认大小
            this.Activate();                           //激活窗体给予焦点
        }

        private void HideWindowsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Hide();                     //隐藏窗体
        }
        /// <summary>
        /// 退出窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExitWindowsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要退出打印机监控程序?", "安全提示",
                        System.Windows.Forms.MessageBoxButtons.YesNo,
                        System.Windows.Forms.MessageBoxIcon.Warning)
                == System.Windows.Forms.DialogResult.Yes)
            {
                notifyIcon1.Visible = false;  //设置图标不可见
                ReleaseCustomResource();
                this.Close();                 //关闭窗体
                this.Dispose();               //释放资源
                Application.Exit();           //关闭应用程序窗体
            }
        }

        /// <summary>
        /// 释放自定义资源
        /// </summary>
        private void ReleaseCustomResource()
        {
            if (ThreadFillPrintTask != null)
            {
                ThreadFillPrintTask.DownloadPrintTaskOverEvent -= ProcDownloadPrintTaskOverEvent;
                ThreadFillPrintTask.StopThread();
            }
            ThreadFillPrintTask = null;
            foreach (var printerMonitor in PrinterMonitorList)
            {
                //取消事件订阅
                printerMonitor.PrintCompleteEvent -= ProcPrintCompleteEvent;
                printerMonitor.StopRunning();
            }
            foreach (var printerMonitor in VirtualPrinterMonitorList)
            {              
                printerMonitor.StopRunning();
            }
            if (MainTaskQueue != null)
            {
                while (!MainTaskQueue.IsEmpty)
                {
                    PrintTaskV2d0 printTask = null;
                    MainTaskQueue.TryDequeue(out printTask);
                }
            }


        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            try
            {
                ReleaseCustomResource();
                ThreadFillPrintTaskStart();
                FirePrintersMonitor();
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }

        }

        private void button3_Click_2(object sender, EventArgs e)
        {
            //PrintLogV2d0 printlog = new PrintLogV2d0();
            ////PrinterInfoSetV2d0 set = new PrinterInfoSetV2d0();

            //HotchPotchV2d0.SaveToXmFile<PrintLogV2d0>(printlog, "d:/printlog.xml");
            FormPrintTempletControl templetControl = new FormPrintTempletControl();
            templetControl.ShowDialog();
        }
        /// <summary>
        /// 处理打印完成事件,写日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="printTask"></param>
        public void ProcPrintCompleteEvent(object sender, PrintTaskV2d0 printTask)
        {
            try
            {
                var traceInfoFinded = TaskTraceInfoList.FirstOrDefault(x => x.TaskUid == printTask.DataOfPrintTask.uid);
                if(traceInfoFinded!=null)
                {
                    traceInfoFinded.PrintFinishTime = DateTime.Now;
                    traceInfoFinded.ActPrinterName = printTask.DataOfPrintTask.act_printer;
                    traceInfoFinded.PrintFinishTime = printTask.DataOfPrintTask.printtime.HasValue ? printTask.DataOfPrintTask.printtime.Value : DateTime.MinValue;
                }
                this.Invoke(
                    new MethodInvoker(
                        delegate ()
                        {
                            bindingSource_TaskTraceInfo.List.Clear();
                            // 进行一次深度复制，避免排序影响原列表
                            List<PrintTaskTraceInfoV2d0> taskTraceInfoListTmp = new List<PrintTaskTraceInfoV2d0>(TaskTraceInfoList.ToArray());
                            taskTraceInfoListTmp.Sort((a, b) => -a.DownloadTime.CompareTo(b.DownloadTime));
                            taskTraceInfoListTmp.ForEach(x => bindingSource_TaskTraceInfo.List.Add(x));
                        }
                    )
                );

                //记录日志
                if (PrintLog != null)
                {
                    PrintLog.PrintLogItemList.Add(new PrintLogItemV2d0(printTask));
                    string xmlFilename = HotchPotchV2d0.GetPrintLogXmlFilename(DateTime.Now);
                    HotchPotchV2d0.SaveToXmFile<PrintLogV2d0>(PrintLog, xmlFilename);
                }
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
        /// <summary>
        /// 任务下载完成事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="printTask"></param>
        public void ProcDownloadPrintTaskOverEvent(object sender, PrintTaskV2d0 printTask)
        {
            try
            {
                PrintTaskTraceInfoV2d0 traceInfo = new PrintTaskTraceInfoV2d0(printTask);
                this.Invoke(
                    new MethodInvoker(
                        delegate ()
                        {
                            int findedIndex = TaskTraceInfoList.FindIndex(x => x.TaskUid == traceInfo.TaskUid);
                            if(findedIndex<0)
                            {
                                bindingSource_TaskTraceInfo.List.Add(traceInfo);
                                TaskTraceInfoList.Add(traceInfo);
                                if (TaskTraceInfoList.Count > 500) TaskTraceInfoList.RemoveAt(0);//最多缓存500个打印记录
                            }
                        }
                    )
                );
                //bindingSource_TaskTraceInfo.List.Add(traceInfo);
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }

        }
        /// <summary>
        /// 处理打印错误事件，写日志
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="printTask"></param>
        public void ProcPrintErrorEvent(object sender, PrintTaskV2d0 printTask)
        {
            //记录日志
            if (PrintLog != null)
            {
                PrintLog.PrintLogItemList.Add(new PrintLogItemV2d0(printTask));
                string xmlFilename = HotchPotchV2d0.GetPrintLogXmlFilename(DateTime.Now);
                HotchPotchV2d0.SaveToXmFile<PrintLogV2d0>(PrintLog, xmlFilename);
            }
        }
        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            
        }

        private void panelPrinterMonitorsHolder_ControlRemoved(object sender, ControlEventArgs e)
        {
            if (e.Control is TmU220PrinterMonitorV2d0)
            {
                var printerMonitor = (e.Control as TmU220PrinterMonitorV2d0);
                printerMonitor.StopRunning();
            }
        }

        private void button4_Click(object sender, EventArgs e)
        {
            FormPrintLogDisplay formPrintLogDisplay = new FormPrintLogDisplay();
            formPrintLogDisplay.ShowDialog();
            GetDataBySQLSingletonV1d0.Instance.Run("select * from rms_printer");
            //ThinkPhpApiGroupSetV1d0 apiSet = new ThinkPhpApiGroupSetV1d0();
            //ThinkPhpApiGroupV1d0 apiTypeTaskApi = new ThinkPhpApiGroupV1d0();
            //apiTypeTaskApi.group_name = "TaskApi";
            //apiTypeTaskApi.api_version = "0.1";
            //apiTypeTaskApi.main_url = "http://api.legendleader.com/index.php/api/rms/";
            //apiTypeTaskApi.ApiList.Add(new ThinkPhpApiV1d0("get","XX", apiTypeTaskApi.main_url, "get","Post","XXX"));
            //apiTypeTaskApi.ApiList.Add(new ThinkPhpApiV1d0("get", "XX", apiTypeTaskApi.main_url, "get", "Post", "XXX"));
            //apiTypeTaskApi.ApiList.Add(new ThinkPhpApiV1d0("get", "XX", apiTypeTaskApi.main_url, "get", "Post", "XXX"));
            //apiTypeTaskApi.ApiList.Add(new ThinkPhpApiV1d0("get", "XX", apiTypeTaskApi.main_url, "get", "Post", "XXX"));
            //ThinkPhpApiGroupV1d0 apiTypePrintTempleteApi = new ThinkPhpApiGroupV1d0();
            //apiTypePrintTempleteApi.group_name = "PrintTempleteApi";
            //apiTypePrintTempleteApi.api_version = "0.1";
            //apiTypePrintTempleteApi.main_url = "http://api.legendleader.com/index.php/api/rms/";
            //apiTypePrintTempleteApi.ApiList.Add(new ThinkPhpApiV1d0("get", "XX", apiTypeTaskApi.main_url, "get", "Post", "XXX"));
            //apiTypePrintTempleteApi.ApiList.Add(new ThinkPhpApiV1d0("get", "XX", apiTypeTaskApi.main_url, "get", "Post", "XXX"));
            //apiTypePrintTempleteApi.ApiList.Add(new ThinkPhpApiV1d0("get", "XX", apiTypeTaskApi.main_url, "get", "Post", "XXX"));
            //apiTypePrintTempleteApi.ApiList.Add(new ThinkPhpApiV1d0("get", "XX", apiTypeTaskApi.main_url, "get", "Post", "XXX"));
            //apiSet.ApiGroupList.Add(apiTypeTaskApi);
            //apiSet.ApiGroupList.Add(apiTypePrintTempleteApi);

            //HotchPotchV2d0.SaveToXmFile<ThinkPhpApiGroupSetV1d0>(apiSet, "d:/phpApiSet.xml");
        }

        /// <summary>
        /// 打印测试按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {

            //Image image = System.Drawing.Image.FromFile("d:/task.bmp");
            //Bitmap bmp = new System.Drawing.Bitmap(image);
            //image.Dispose();
            foreach (var monitor in VirtualPrinterMonitorList)
            {
                if(monitor.IsPrinterReady)
                {
                    PrintTaskV2d0 printTask = GetPrintTaskOfPrinterTesting(monitor);
                    //printTask.PrintTaskItemList[0].BitmapOfContent = bmp;
                    MainTaskQueue.Enqueue(printTask);
                }
            }
        }
        /// <summary>
        /// 打印任务分发循环
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerTaskDispatch_Tick(object sender, EventArgs e)
        {
            TaskDispatch();
        }
        /// <summary>
        /// 任务分派
        /// </summary>
        private void TaskDispatch()
        {
            try
            {
                //是否至少有一个正常的打印机,否则返回
                bool isAtLeastOneNormalPrinter = false;
                //var normalPrinter = PrinterMonitorList.FirstOrDefault(x => x.IsConnected && x.IsPrinterReady);
                var normalPrinter = VirtualPrinterMonitorList.FirstOrDefault(x => x.IsConnected && x.IsPrinterReady);
                if (normalPrinter != null)
                {
                    isAtLeastOneNormalPrinter = true;
                    this.Text = TitleBarString;
                    notifyIcon1.Icon = iconNormal;
                }
                else
                {
                    isAtLeastOneNormalPrinter = false;
                    this.Text = TitleBarString + "****注意，没有可正常使用的打印机！";
                    notifyIcon1.Icon = iconError;
                    return;
                }
                // 得到工作正常的打印机列表
                var printerMonitorListNormal = VirtualPrinterMonitorList.FindAll(x => x.IsPrinterReady && x.IsConnected);
                // 打印任务
                PrintTaskV2d0 printTask = null;
                // 如果成功取出一个打印任务，并且该打印任务未超时
                if (MainTaskQueue.TryDequeue(out printTask))
                    {
                    // 该打印任务的目标打印机
                    string targetPrinterNameOfTask = printTask.DataOfPrintTask.printer;
                    // 任务的主打印机名词，备份打印机名称
                    var majorPrinerMonitorOfTask = VirtualPrinterMonitorList.FirstOrDefault(x => x.PrinterName == targetPrinterNameOfTask);
                    //var majorPrinerMonitorOfTask = PrinterMonitorList.FirstOrDefault(x => x.PrinterName == targetPrinterNameOfTask&&x.IsConnected&&x.IsPrinterReady);
                    string majorPrinterNameOfTask = "";
                    string backupPrinterNameOfTask = "";

                    if (majorPrinerMonitorOfTask!=null)
                    {
                        majorPrinterNameOfTask = majorPrinerMonitorOfTask.PrinterName;
                        backupPrinterNameOfTask = majorPrinerMonitorOfTask.BackupPrinterName;
                    }
                    else
                    {
                        //如果没有找到主打印机的监控器，则将该任务写回主任务队列
                        MainTaskQueue.Enqueue(printTask);
                        return;
                    }

                    // 在正常打印机监控器列表中进行查询
                    var majorMonitorFinded = printerMonitorListNormal.FirstOrDefault(x => x.PrinterName == majorPrinterNameOfTask);
                    var backupMonitorFinded = printerMonitorListNormal.FirstOrDefault(x => x.PrinterName == backupPrinterNameOfTask);

                    if (majorMonitorFinded != null) {
                        // 如果主打印机正常，就将任务发送给主打印机
                        majorMonitorFinded.AddPrintTaskToQueue(printTask);
                    }
                    else if(backupMonitorFinded!=null)
                    {
                        //如果主打印机不正常，但备份打印机正常，就将任务发送给备份打印机
                        backupMonitorFinded.AddPrintTaskToQueue(printTask);
                    }
                    else
                    {
                        //如果主打印机和备份打印机都不正常，则将任务写回主任务队列
                        MainTaskQueue.Enqueue(printTask);
                    }
                }              
            }
            catch(Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
        /// <summary>
        /// 检查打印机是否正常
        /// </summary>
        /// <param name="printerMonitor"></param>
        /// <returns></returns>
        private bool CheckPrinterIsNormal(TmU220PrinterMonitorV2d0 printerMonitor)
        {
            if (printerMonitor.IsConnected && printerMonitor.IsPrinterReady) return true;
            else return false;
        }

        private void contextMenuStrip1_DoubleClick(object sender, EventArgs e)
        {
                       //激活窗体给予焦点
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            this.Show();                               //窗体显示
            this.WindowState = FormWindowState.Normal;  //窗体状态默认大小
            this.Activate();                           //激活窗体给予焦点
        }

        private void button6_Click(object sender, EventArgs e)
        {
            try
            {
                ShowFormPrinterSetting();
                ReleaseCustomResource();
                ThreadFillPrintTaskStart();
                FirePrintersMonitor();
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
        /// <summary>
        /// 显示打印机配置窗口
        /// </summary>
        private void ShowFormPrinterSetting()
        {
            FormPrinterSetting formPrinterSetting = new FormPrinterSetting();
            formPrinterSetting.ShowDialog();
            PrinterInfoSet = formPrinterSetting.InfoSet;
            TaskApiUrl = formPrinterSetting.TaskApiUrl;
            //释放资源
            ReleaseCustomResource();
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void button1_Click_1(object sender, EventArgs e)
        {
            //var yyy=SysCfgInfoSingletonV1d0.Instance.GetSysCfgInfo();
            //var xxx = ConfigurationManager.AppSettings;
            //var xxx = System.Configuration.
            //var xxx = ConfigurationSettings.GetConfig("userSettings");
            //rms_order_print_main printMain = new rms_order_print_main();
            //printMain.id = 2;
            //printMain.status = 1;
            //printMain.printtime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            //printMain.act_printer = "test";
            //JObject jsonObject = new JObject {{ "status", "1" } ,
            //                                { "printtime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") },
            //                                { "act_printer", "test" }
            //                            };
            //string jsonStringOfData = JsonConvert.SerializeObject(jsonObject);
            //bool result=UpdateDataKeyValueDataNetSingletonV1d0.Instance.Run("rms_order_print_main","id", "2", jsonStringOfData);
            //RouterPhp接口测试
            //GetData接口测试
            //ConfigurationManag.er.
            //var xxx = ConfigurationManager.ConnectionStrings[connectionName].ConnectionString.ToString();
            //int timeOutOfTask = Convert.ToInt32(System.Configuration.ConfigurationSettings.GetConfig("userSettings")["TimeoutOfTask"].ToString());
            try
            {

                List<rms_order_print_main> printMainletList =
                    JsonConvert.DeserializeObject<List<rms_order_print_main>>(GetDataSingletonV1d0.Instance.Run("rms_order_print_main"));
                if (printMainletList != null) MessageBox.Show("共得到rms_order_print_main表" + printMainletList.Count + "条记录！");
            }
            catch(Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
        /// <summary>
        /// 设置任务在固定时间启动
        /// </summary>
        private void startCleanAtFixedTime()
        {
            try
            {
                DateTime now = DateTime.Now;
                DateTime oneOClock = DateTime.Today.AddHours(SysCfgInfoSingletonV1d0.Instance.GetSysCfgInfo().HourOfClean); //凌晨1：00
                if (now > oneOClock)
                {
                    oneOClock = oneOClock.AddDays(1.0);
                }
                int msUntilFour = (int)((oneOClock - now).TotalMilliseconds);
                var t = new System.Threading.Timer(doClean);
                t.Change(msUntilFour, Timeout.Infinite);
            }
            catch(Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
        /// <summary>
        /// 系统清理
        /// </summary>
        /// <param name="state"></param>
        private void doClean(object state)
        {
            try
            {
                //执行功能...
                string currDir = System.IO.Directory.GetCurrentDirectory();
                string logDir = currDir + @"\logs";
                DirectoryInfo dirInfo = new DirectoryInfo(logDir);
                int lifeHoursOfLogFile = SysCfgInfoSingletonV1d0.Instance.GetSysCfgInfo().LifeHoursOfLogFile;
                var fileInfos = dirInfo.GetFiles().ToList();
                var fileInfosToBeClean = fileInfos.FindAll(x => (DateTime.Now - x.CreationTime).TotalHours > lifeHoursOfLogFile);
                fileInfosToBeClean.ForEach(x => x.Delete());
                SimpleLoger.Instance.Info("完成日志文件清理:"+ DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
                //再次设定
                startCleanAtFixedTime();
            }
            catch (Exception ex)
            {
                SimpleLoger.Instance.Error(ex);
            }
        }
    }
}
